package com.lc.tools;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;

import java.util.HashSet;
import java.util.Set;

/**
 * 复制对象属性工具类
 *
 * @author wwk
 * @version 1.0, 2019-01-16
 * @see
 * @since 1.0
 */
public class BeanUtils {

    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            if (pd.getName().indexOf("Date") != -1 && pd.getName().indexOf("Str") != -1) {
                //FIXME 该判定有可能误过滤掉自定义的属性
            }else {
                Object srcValue = src.getPropertyValue(pd.getName());
                if (srcValue == null) emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    public static void copyProperties(Object source, Object target) throws BeansException {
        org.springframework.beans.BeanUtils.copyProperties(source, target);
    }

    public static void copyPropertiesIgnoreNull(Object source, Object target) throws BeansException {
        org.springframework.beans.BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }


}
